package org.example.controller.supplier;

import org.example.entity.Supplier;
import org.example.service.SupplierService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/supplier/search")
public class querySupplierController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //先设置编码
        req.setCharacterEncoding("utf-8");
        //获取页面的输入，默认为按名称搜索
        String name = req.getParameter("keyword");
        //实例化实现类
        SupplierService supplierService = new SupplierService();
        //调用实现类的查询方法
        Supplier supplier = new Supplier();
        supplier.setName(name);
        try {
            List<Supplier> supplierList = new ArrayList<>();
            Supplier supplier1 = supplierService.queryMatchSupplier(supplier);
            System.out.println(supplier1.getName());
            if(supplier1.getName()!=null){
                supplierList.add(supplier1);
                req.setAttribute("data",supplierList);
                req.getRequestDispatcher("/suppliers/supplier.jsp").forward(req,resp);
            }else{
                PrintWriter out = resp.getWriter();
                out.print("<script>alert(' no record found...'); window.location='/supplier' </script>");
                out.flush();
                out.close();
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }
}
